<template>
	<view class="page">
		<template v-if="scrollTop<=450">
			<view class="backBox" :style="{top:menuTop+'px'}">
				<view class="Vr" style="padding: 10rpx;border-radius: 100%;">
					<u-icon name='arrow-left' color='#fff' @click='$utils.back()' size='30rpx' />
				</view>
			</view>
			<view v-if="!loading" :style="{top:menuTop+'px',right:menuRight+20+'px',height:menuHeight+'px'}"
				class="VrBox">
				<view @click="changeimage" v-if="myUser.id==detail.user_id" class="Vr"
					style="border-radius: 100%;padding: 10rpx;">
					<text class="icon-tupian iconfont" style="margin-right: 0;" />
				</view>

				<view @click="clickImage" v-if='detail.qr_group' class="Vr" style="border-radius: 100%;padding: 10rpx;">
					<text class="icon-kehu iconfont" style="margin-right: 0;" />
				</view>
			</view>
		</template>
		<u-navbar v-else title="挑战详情" border @leftClick="$utils.back()" placeholder>
		</u-navbar>
		<view style="flex: 1;">
			<template v-if="type=='active'">

				<view v-if="!loading&&!isPublishedToday&&isAttended" class="bottom" @click="jumpActive">
					<u-icon name='camera' color='#fff' size='60rpx' />
				</view>
				<view v-if="!loading&&myUser.id&&isAttended" style="bottom: 17vh;" class="bottom" @click="jumpUser(myUser.id)">
					<u-avatar :src='myUser.avatar' size='100rpx'/>
				</view>
			</template>
			<z-paging ref="paging" style="height: 100%;" :fixed="false" v-model="List" @query="query"
				:default-page-no="1" :hide-empty-view='true' :default-page-size="10" :auto="false" @scroll='scroll'>
				<view class="background">
					<image mode="aspectFill" v-if="type=='active'" :src="detail.thumb" class="masking"
						style="z-index:1;background: transparent;"></image>
					<image mode="aspectFill" v-else :src="rankUser.cover" class="masking"
						style="z-index:1;background: transparent;"></image>
					<view class="masking" v-if="!loading" />
					<view class="masking" v-else />
					<view v-if="type=='active'" class="userBox" :style="{top:menuTop+80+'px'}">
						<u-avatar mode='aspectFill' :src='user.avatar' size='100rpx' @click.stop='jumpUser(user.id)' />
						<view style="width: 20rpx;"></view>
						<view style="flex: 1;">
							<u-text :lines='1' :text='user.nick_name' color='#fff' />
							<view style="height: 20rpx;"></view>
							<view style="display: flex;">
								<view>
									<u--text lines='1' :iconStyle='{color:"#fff"}' prefixIcon='map' color='#fff'
										:text='detail.title' size='24rpx' />
								</view>
							</view>
						</view>
					</view>
					<view v-else :style="{top:menuTop+50+'px'}" class="rankBox">
						<view class="rankTime">
							{{$u.timeFormat(new Date(), 'yyyy/mm/dd')}}
						</view>
						<view class="rankUserBox" style="position: static;">
							<u-avatar mode='aspectFill' :src='rankUser.avatar' shape='square' size='60rpx'
								@click.stop='jumpUser(rankUser.id)' />
							<view style="width: 20rpx;"></view>
							<view style="flex: 1;">
								<u-text :lines='1' size='24rpx' :text='rankUser.nick_name' color='#fff' />
							</view>
						</view>
					</view>
					<view class="Followed viewWidth" v-if="!loading">
						<view @click.stop="Followed" class="Vr ">
							<u-icon v-if="!isFollowed" color='#fff' labelColor='#fff' name="heart" size="24rpx"
								labelSize='28rpx' label='关注'></u-icon>
							<u-icon v-else color='#fff' labelColor='#fff' name="heart-fill" size="24rpx"
								labelSize='28rpx' label='取消关注'></u-icon>
						</view>
						<view @click.stop="Thumbsup" class="Vr ">
							<u-icon v-if="!isThumbsuped" color='#fff' labelColor='#fff' name="thumb-up" size="24rpx"
								labelSize='28rpx' label='点赞'></u-icon>
							<u-icon v-else color='#fff' labelColor='#fff' name="thumb-up-fill" size="24rpx"
								labelSize='28rpx' label='取消点赞'></u-icon>
						</view>
						<view class="Vr " v-if="is_public" style="justify-content: space-between;
    width: 48vw;
    background: none;">
							<view @click="typeChange" class="Vr ">
								<template v-if="type=='active'">
									<text class="icon-shuzhuangtu iconfont" />
									<text>排名</text>
								</template>
								<template v-else>
									<text class="icon-tupian iconfont" />
									<text>动态</text>
								</template>
							</view>

							<view style="bottom: 30rpx;
							color: #fff;
							display: flex;
							align-items: center;
								right: 40rpx;
								left: auto;" class='calendar'>
								<text>
									第
								</text>
								<text class=" Vr">
									{{getTimeDifferenceInDays(detail.start_at,new Date())}}
								</text>
								<text>
									天
								</text>
							</view>
						</view>
					</view>
					<view class="radius" />
				</view>
				<template v-if="type=='active'">
					<view class="viewWidth InfoBox">
						<view class="title">
							<u-icon name="attach" size="40rpx" labelSize='24rpx' label='目标信息'></u-icon>
						</view>
						<view class="infoContent" v-if='loading'>
							<view style="width: 50%;">
								<view class="mb20">
									<view style="height: 30rpx;width: 80%;" class="Skeleton" />
								</view>
								<view class="mb20">
									<view style="height: 30rpx;width: 80%;" class="Skeleton" />
								</view>
							</view>
							<view style="width: 50%;">
								<view class="mb20">
									<view style="height: 30rpx;width: 80%;" class="Skeleton" />
								</view>
								<view class="mb20">
									<view style="height: 30rpx;width: 80%;" class="Skeleton" />
								</view>
							</view>
						</view>
						<view class="infoContent " v-else>
							<view style="width: 50%;">
								<view class="mb20">
									<u--text lines='1' size='24rpx' :text='`目标减重：${detail.weight}Kg`' />
								</view>
								<view class="mb20">
									<u--text lines='1' size='24rpx' :text='`天数：${detail.days}天`' />
								</view>
							</view>
							<view style="width: 50%;">
								<view class="mb20">
									<u--text lines='1' size='24rpx' :text='`开始日期：${detail.start_at}`' />
								</view>
								<view class="mb20">
									<u--text lines='1' size='24rpx' :text='`参加人数：${detail.user_count}`' />
								</view>
							</view>
						</view>
					</view>
					<view class="InfoBox viewWidth" v-if="userList.length">
						<view class="title">
							<u-icon name="account" size="40rpx" labelSize='24rpx' label='用户'></u-icon>
						</view>
						<view style="display:flex;" class="viewWidth" v-if="loading">
							<view v-for="(item,index) in [1,2,3,4,5]" :key="index" class="access ">
								<view style="width: 100rpx;height: 100rpx;border-radius:100% ;" class="Skeleton">

								</view>
								<view style="width: 100rpx;height: 20rpx;" class="Skeleton">
								</view>
							</view>
						</view>
						<view style="display:flex;overflow: auto;" class="viewWidth" v-else>
							<view v-for="(item,index) in userList" :key="index" class="access">
								<view style="position: relative;">
									<u-badge v-if="item.total_different_weight<0" bgColor='red' :offset='[-5,-5]'
										absolute='true' :value="`${0-item.total_different_weight}kg`" />
									<u-badge v-if="item.total_different_weight>=0" bgColor='green' :offset='[-5,-5]'
										absolute='true' :value="`${item.total_different_weight}kg`" />
									<u-avatar mode='aspectFill' @click.stop='jumpUser(item.user.id)'
										:src="item.user.avatar" size='100rpx'></u-avatar mode='aspectFill'>
								</view>
								<view style="margin-top: 20rpx;height: 40rpx;">
									<u--text lines='1' size='26rpx' :text='item.user.nick_name' />
								</view>
							</view>
						</view>
					</view>

				</template>
				<template v-if="type=='active'">
					<view class="viewWidth InfoBox ">
						<view class="title">
							<u-icon name="bell" size="40rpx" labelSize='24rpx' label='打卡记录'></u-icon>
						</view>
						<clock />
					</view>
				</template>
				<view class="viewWidth InfoBox contentBox">
					<view class="title">
						<u-icon name="photo" size="40rpx" labelSize='24rpx' :label='type=="rank"?"排名":"动态"'></u-icon>
					</view>
					<ranking v-if="type=='rank'" :list='List' :myRankUser='myRankUser' :conquer_id='conquer_id' />
					<active v-else @reload='$refs.paging.reload()' :list='List' :loading='Listloading' ref='active'
						:playIndex='playIndex' :conquer_id='conquer_id' :weight='detail.weight'
						:start_at='detail.start_at' @ListloadingChange='Listloading!=Listloading' />
				</view>
			</z-paging>

		</view>
		
	</view>
</template>

<script>
	import ranking from './components/ranking'
	import user from './components/user'
	import active from './components/active'
	import clock from './components/clock'
	export default {
		components: {
			ranking,
			active,
			user,
			clock
		},
		data() {
			return {
				isAttended:false,
				is_public: false,
				isThumbsuped: false,
				myUser: uni.getStorageSync('user'),
				isFollowed: false,
				myRankUser: {},
				rankUser: {},
				playIndex: 0,
				isPublishedToday: false,
				Listloading: true,
				userList: [],
				List: [],
				type: 'active',
				detail: {},
				loading: true,
				menuHeight: 0,
				menuRight: 0,
				conquer_id: 0,
				menuTop: 0,
				scrollTop: 0,
				navbarTop: 0,
				user: {},
				token: uni.getStorageSync('token'),
			}
		},
		
		onShareAppMessage() {
		
			return {
				title: this.detail.title,
				path: '/Conquer/Detail?id=' + this.conquer_id,
				imageUrl: this.detail.thumb
			};
		},
		//2.分享到朋友圈
		onShareTimeline() {
			return {
				title: this.detail.title,
				path: '/Conquer/Detail?id=' + this.conquer_id,
				imageUrl: this.detail.thumb
			};
		},
		onLoad(op) {
			this.conquer_id = op.id
			this.getDateil(op.id)
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect() //可以获取小程序胶囊的位置。
			this.menuTop = menuButtonInfo.top
			this.menuRight = menuButtonInfo.width
			this.menuHeight = menuButtonInfo.height
			let res = uni.getSystemInfoSync()
			this.navbarTop = res.statusBarHeight + 44 //顶部状态栏+顶部导航，大部分机型默认44px
		},
		methods: {
			clickImage() {
				uni.setStorageSync('imageList',
					[{
						url: this.detail.qr_group,
						title: ''
					}]
				);
				this.$utils.navigateTo({
					url: '/Image/show?index=' + 0
				})
			},
			getTimeDifferenceInDays(timestamp1, timestamp2) {
				// 将时间戳转换为日期对象
				const date1 = new Date(timestamp1);
				const date2 = new Date(timestamp2);

				// 计算两个日期之间的毫秒差
				const timeDifferenceInMilliseconds = Math.abs(date2 - date1);

				// 将毫秒转换为天数，一天有 24 * 60 * 60 * 1000 毫秒
				const oneDayInMilliseconds = 24 * 60 * 60 * 1000;
				const differenceInDays = Math.ceil(timeDifferenceInMilliseconds / oneDayInMilliseconds);

				return differenceInDays - 1;
			},
			daysBetween(date) {
				// 将输入转换为Date对象
				const d1 = new Date();
				const d2 = new Date(date);

				// 计算两个日期的时间戳差值（毫秒）
				const differenceInMilliseconds = Math.abs(d2 - d1);

				// 转换为天数（一天有86400000毫秒）
				const oneDay = 86400000;
				return Math.ceil(differenceInMilliseconds / oneDay); // 返回整数天数，因为Math.ceil向上取整
			},
			Thumbsup() {
				if (!this.token) {
					setTimeout(() => {
						this.$utils.judgeToken()
					}, 500)
					uni.$u.toast('未登录请先登录')
					return
				}
				if (this.isThumbsuped) {
					uni.$u.toast('取消点赞')
					this.thumbsupers = this.thumbsupers.filter(item => item.avatar != uni.getStorageSync('user').avatar)
				} else {
					uni.$u.toast('点赞成功')
					this.thumbsupers.push({
						avatar: uni.getStorageSync('user').avatar
					})
				}
				this.isThumbsuped = !this.isThumbsuped
				this.$api.Thumbsup.Thumbsup('conquer', this.conquer_id)

			},
			changeimage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						res.tempFilePaths.forEach((item, index) => {
							uni.uploadFile({
								url: this.$config.url +
									'/api/conquer/image/upload', //仅为示例，非真实的接口地址
								filePath: item,
								name: 'file',
								formData: {
									'conquer_id': this.conquer_id
								},
								header: {
									'Content-Type': 'application/json;charset=UTF-8',
									'Authorization': "Bearer " + uni.getStorageSync('token')
								},
								success: (res) => {
									this.detail.thumb = item
								},
							});
						})

					},
					fail: () => {

					}
				})
			},
			Followed() {
				if (!this.token) {
					setTimeout(() => {
						this.$utils.judgeToken()
					}, 500)
					uni.$u.toast('未登录请先登录')
					return
				}
				if (this.isFollowed) {
					uni.$u.toast('取消关注')
					this.$api.Followed.DelFollow({
						user_id: this.detail.user_id
					}).then(res => {}).catch(err => {
						uni.$u.toast(err.data.message)
						this.isFollowed = !this.isFollowed
					})
				} else {
					uni.$u.toast('关注成功')
					this.$api.Followed.Follow({
						user_id: this.detail.user_id
					}).then(res => {}).catch(err => {
						uni.$u.toast(err.data.message)
						this.isFollowed = !this.isFollowed
					})
				}
				this.isFollowed = !this.isFollowed

			},
			jumpActive() {
			
				if (!this.token) {
					setTimeout(() => {
						this.$utils.judgeToken()
					}, 500)
					uni.$u.toast('未登录请先登录')
					return
				}
				this.$utils.navigateTo({
					url: '/Active/add?id=' + this.conquer_id
				})
			},
			jumpUser(id) {
				this.$utils.navigateTo({
					url: '/User/detail?id=' + id + '&conquer_id=' + this.conquer_id
				})
			},
			getDateil(id) {
				uni.showLoading({
					title: '加载中...'
				})
				this.$api.Conquer.Detail(id).then(res => {
					this.isFollowed = res.data.isFollowed
					this.isAttended=res.data.isAttended
					this.isThumbsuped = res.data.isThumbsuped
					this.detail = res.data.conquer
					this.is_public = this.detail.is_public
					this.user = res.data.conquer.user
					this.rankList = res.data.activities.data
					this.userList = res.data.activities
					this.isPublishedToday = res.data.isPublishedToday
					this.loading = false
					this.query(1, 10)
				}).catch(err => {
					uni.hideLoading()
				})
			},
			scroll(e) {
				const top = e.detail.scrollTop
				this.scrollTop = top * 2
				let index = 0
				let domTop0 = 0
				const query = uni.createSelectorQuery().in(this.$refs.active);
				query.selectAll('.activeBox').boundingClientRect(data => {
					data.forEach((rect, domIndex) => {
						let domTop = rect.top + top
						if (domIndex == 0) {
							domTop0 = domTop
						}
						if (top > (domTop - domTop0)) {
							index = domIndex
						}
						if (domIndex == data.length - 1) {
							this.playIndex = index

						}
					});
				}).exec();
			},
			typeChange() {
				this.Listloading = true
				this.$refs.paging.reload()
				if (this.type == 'rank') {
					this.type = 'active'
				} else {
					this.type = 'rank'
				}
			},
			query(page, size) {
				let obj = {
					page,
					size,
					conquer_id: this.conquer_id
				}
				uni.showLoading({
					title: '加载中...'
				})

				if (this.type == 'rank') {
					this.$api.Active.Rank.List(obj).then(res => {
						if (!res.data.activities.data.length) {
							this.typeChange()
							uni.$u.toast('暂无排名')
							return
						}
						this.Listloading = false
						this.$refs.paging.complete(res.data.activities.data)
						if (res.data.activities.data.length) {
							this.rankUser = {
								...res.data.activities.data[0].user,
								cover: res.data.firstUser.cover
							}
						}
						this.myRankUser = {
							...res.data.myTodayRank,
							rank: res.data.rank,
							user: this.myUser
						}
						console.log(this.myRankUser)
						uni.hideLoading()
					}).catch(err => {
						uni.hideLoading()
					})
				} else {
					this.$api.Active.List(this.conquer_id, obj).then(res => {
						this.Listloading = false
						this.$refs.paging.complete(res.data.fragments.data.map(item => {
							return {
								...item,
								user: res.data.users[item.user_id]
							}
						}))
						uni.hideLoading()
					}).catch(err => {
						uni.hideLoading()
					})
				}

			}

		}
	}
</script>

<style lang="scss" scoped>
	.InfoBox {
		margin: 20rpx auto;
		background-color: #fff;
		box-shadow: 0 0 10rpx #ddd;
		padding: 10rpx;
		border-radius: 8rpx;

		.title {
			width: 100%;
			border-bottom: 1rpx solid #ddd;
			margin: 0 0 20rpx;
		}

		.infoContent {
			display: flex;
			width: 100%;
			justify-content: space-between;
		}
	}

	.page {
		height: 100vh;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 10rpx);
		/* 兼容 iOS 设备 */
		padding-bottom: calc(env(safe-area-inset-bottom) + 10rpx);
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
	}

	.stepsBox {
		padding: 0rpx 20rpx;
		height: 100rpx;
		position: absolute;
		z-index: 1;
		display: flex;
		overflow: auto;
	}

	.fff {
		background-color: #fff;
		width: 100%;
		z-index: 111;
	}



	.contentBox {
		flex: 1;
		position: relative;
	}

	.background {
		height: 500rpx;
		width: 100%;
		position: relative;
	}

	.masking {
		background: linear-gradient(to top, rgba(0, 0, 0, 0.3), rgba(255, 255, 255, 0), rgba(255, 255, 255, 0));
		position: absolute;
		width: 100%;
		height: 500rpx;
		z-index: 2;
	}

	.backBox {
		position: fixed;
		left: 40rpx;
		z-index: 1111111111;
	}

	.Vr {
		background: rgba(0, 0, 0, 0.3);
		padding: 10rpx 20rpx;
		border-radius: 100rpx;
		color: #fff;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;

		>button {
			opacity: 0;
			position: absolute;
			z-index: 1;
			width: 100%;
			height: 100%;
			top: 0;
			left: 0;
		}
	}

	.VrBox {
		display: flex;
		position: absolute;
		align-items: center;
		z-index: 111;

		>view {
			margin-right: 10rpx;
		}
	}

	.iconfont {
		margin-right: 10rpx;
		font-size: 24rpx;
	}

	.userBox {
		display: flex;
		position: absolute;
		width: 90vw;
		left: 40rpx;
		z-index: 111;
	}

	.radius {
		position: absolute;
		bottom: 0;
		height: 20rpx;
		width: 100vw;
		background-color: #f5f5f5;
		border-radius: 16rpx 16rpx 0 0;
		z-index: 11;
	}

	.bottom {
		position: fixed;
		bottom: 10vh;
		right: 5vw;
		width: 100rpx;
		height: 100rpx;
		background-color: #999;
		border-radius: 16rpx 16rpx 0 0;
		z-index: 11;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 100%;
	}

	.access {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 26rpx;
		text-align: center;
		margin-top: 20rpx;
		margin-right: 20rpx;
		width: 100rpx;
	}

	.rankBox {
		left: 40rpx;
		position: absolute;
		z-index: 1;

		.rankTime {
			color: #fff;
			font-size: 35rpx;
			margin-bottom: 10rpx;
		}

		.rankUserBox {
			display: flex;
			align-items: center;
		}
	}

	.Followed {
		margin-bottom: 0;
		z-index: 11111;
		position: absolute;
		left: 40rpx;
		bottom: 40rpx;
		display: flex;
		align-items: center;

		>view {
			margin-right: 10rpx;
			border-radius: 100rpx;
		}
	}

	.startBox {
		font-size: 26rpx;
		color: #fff;
		text-align: right;
	}

	.add {
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50rpx;
		width: 200rpx;
		position: fixed;
		margin: auto;
		left: 0;
		right: 0;
		bottom: calc(constant(safe-area-inset-bottom) + 10rpx);
		/* 兼容 iOS 设备 */
		bottom: calc(env(safe-area-inset-bottom) + 10rpx);
		background: linear-gradient(to top, #3573be, #489aff);
	}
</style>